import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:kegelutils/bean/bean_day_event.dart';
import 'package:kegelutils/dailogs.dart';
import 'package:kegelutils/state_player.dart';
import 'package:kegelutils/storage/get_storage_instance.dart';
import 'package:kegelutils/storage/storage_keys.dart';
import 'package:kegelutils/utils/calendar_event.dart';

class MainController extends GetxController {
  static MainController get to => Get.find();

  final duration = Duration.zero.obs;
  final position = Duration.zero.obs;
  final state = PlayState.stopped.obs;

  final curStep = 1.obs;
  final curMaxStep = 50.obs;
  late AudioPlayer _player;

  static const int INDEX_NO_CHECK_PLAN = 100;
  int lastPageIndex = 0;

  final planIndex = 0.obs;
  final curRunningIndex = 100.obs;
  late int stepDuration = 3;

  late PageController pageController;
  late PageController remainTimeController;

  void setupPlanInfo() {
    // planIndex.value =
    //     SpInstance.getInstance().getInt(SpKeys.PLAN_INDEX, defaultV: 0);
    // planIndex.refresh();
    initSoundInfo();
    initPageController();
  }

  void initSoundInfo() {
    String? soundPath;
    switch (planIndex.value) {
      case 0:
        soundPath = 'sounds/step_1.mp3';
        stepDuration = 3;
        break;
      case 1:
        soundPath = 'sounds/step_2.mp3';
        stepDuration = 3;
        break;
      case 2:
        soundPath = 'sounds/step_3.mp3';
        stepDuration = 3;
        break;
      case 3:
        soundPath = 'sounds/step_4.mp3';
        stepDuration = 3;
        break;
      default:
        soundPath = 'sounds/step_1.mp3';
        stepDuration = 3;
        break;
    }
    _player = AudioPlayer();
    _player.setSourceAsset(soundPath);

    ///获取长度
    _player.onDurationChanged.listen((duration) {
      curMaxStep.value = duration.inSeconds ~/ stepDuration + 1;
      curMaxStep.refresh();
      curStep.value = 1;
      curStep.refresh();

      MainController.to.duration.value = duration;
      MainController.to.duration.refresh();
    });

    ///获取当前进度
    _player.onPositionChanged.listen((p) {
      curStep.value = p.inSeconds ~/ stepDuration + 1;
      curStep.refresh();
      position.value = p;
      position.refresh();
    });

    ///监听完成
    _player.onPlayerComplete.listen((event) {
      state.value = PlayState.completed;
      state.refresh();
      if (state.value == PlayState.completed) {
        int curRunningIndex = MainController.to.curRunningIndex.value;
        int curTimeMills = DateTime.now().millisecondsSinceEpoch;
        int positionSeconds = position.value.inSeconds;
        Event event = Event.fromParams(
          createTime: curTimeMills,
          type: curRunningIndex,
          duration: positionSeconds,
        );
        // EventsController.to.monthEvents.add(event);
        // EventsController.to.monthEvents.refresh();
        // EventsController.to.todayEvents.add(event);
        // EventsController.to.todayEvents.refresh();
        CalendarUtils.saveDateEvent(event);
        position.value = Duration.zero;
        position.refresh();
        popDialog(
            Center(
              child: RichText(
                text: TextSpan(
                  text: '您已完成 ',
                  style: const TextStyle(
                    fontSize: 18.0,
                    color: Colors.black87,
                  ),
                  children: [
                    TextSpan(
                      text: MainController.buildPlanTitle(curRunningIndex),
                      style: const TextStyle(
                        fontWeight: FontWeight.bold,
                        color: Colors.deepPurple,
                        fontSize: 20.0,
                      ),
                    ),
                    const TextSpan(
                      text: ' 的训练。',
                      style: TextStyle(
                        fontSize: 18.0,
                        color: Colors.black87,
                      ),
                    ),
                  ],
                ),
              ),
            ), onPositiveTap: () {
          Get.back();
        });
      }
    });
  }

  void changeSoundPath() {
    if (MainController.to.state.value != PlayState.stopped &&
        MainController.to.state.value != PlayState.completed) {
      stop();
    }

    _player = AudioPlayer();

    initSoundInfo();
  }

  void initPageController() {
    pageController = PageController(initialPage: 0, keepPage: true);
    pageController.addListener(() {
      double? curPage = pageController.page;
      // print("curPage= $curPage");
      planIndex.value = (curPage ?? 0) ~/ 1;
      planIndex.refresh();
      if (planIndex.value != lastPageIndex) {
        lastPageIndex = planIndex.value;
        if (curRunningIndex.value == INDEX_NO_CHECK_PLAN) {
          changeSoundPath();
        }
      }
      SpInstance.getInstance().setInt(SpKeys.PLAN_INDEX, planIndex.value);
    });
    remainTimeController = PageController(initialPage: 0, keepPage: true);
    remainTimeController.addListener(() {});
  }

  void play({bool? reset}) async {
    MainController.to.state.value = PlayState.playing;
    MainController.to.state.refresh();
    curRunningIndex.value = planIndex.value;
    curRunningIndex.refresh();

    if (reset ?? false) {
      MainController.to.position.value = Duration.zero;
      MainController.to.position.refresh();
    }
    await _player.seek(MainController.to.position.value);
    // await _player.seek(Duration(minutes: 10));
    await _player.resume();
  }

  void paused() async {
    MainController.to.state.value = PlayState.paused;
    MainController.to.state.refresh();
    await _player.pause();
  }

  void stop() async {
    MainController.to.state.value = PlayState.stopped;
    MainController.to.state.refresh();

    await _player.stop();

    int mCurRunningIndex = MainController.to.curRunningIndex.value;
    int mCurTimeMills = DateTime.now().millisecondsSinceEpoch;
    int positionSeconds = position.value.inSeconds;
    Event event = Event.fromParams(
      createTime: mCurTimeMills,
      type: mCurRunningIndex,
      duration: positionSeconds,
    );
    // EventsController.to.monthEvents.add(event);
    // EventsController.to.monthEvents.refresh();
    // EventsController.to.todayEvents.add(event);
    // EventsController.to.todayEvents.refresh();
    CalendarUtils.saveDateEvent(event);
    position.value = Duration.zero;
    position.refresh();

    curRunningIndex.value = INDEX_NO_CHECK_PLAN;
    curRunningIndex.refresh();
    MainController.to.position.value = Duration.zero;
    MainController.to.position.refresh();
  }

  ///构建训练计划标题
  static String buildPlanTitle(int index) {
    String title = '';
    switch (index) {
      case 0:
        title = '基础训练';
        break;
      case 1:
        title = '加速训练';
        break;
      case 2:
        title = '持久训练';
        break;
      case 3:
        title = '混合训练';
        break;
    }
    return title;
  }

  static List<Event> getSaveEvents() {
    DateEvents curMonthEvents = CalendarUtils.getDateEvents();
    List<Event?> events = curMonthEvents.events ?? [];
    events.removeWhere((element) => element == null);
    List<Event> result = [];
    for (var event in events) {
      result.add(event!);
    }
    return result;
  }
}
